import tkinter as tk
from tkinter import messagebox
import pandas as pd
from datetime import datetime
import os
from tkinter import ttk

def show_outgoing_records(text_outgoing_view, root):
    '''
    当出库成功后
    将本日出库记录布局到出库页面的文本框中
    '''
    datenow = datetime.now().strftime("%Y/%m/%d")
    file_path = f"出库/{datenow}.xlsx"
    
    # 尝试读取当日出库数据
    try:
        df = pd.read_excel(file_path)   # 读取今日日期所对应的文件
        text_outgoing_view.delete(1.0, tk.END)  # 清空文本框内容
        text_outgoing_view.insert(tk.END, df.to_csv(sep='\t', na_rep='nan'))    # 在文本框内插入当日出库信息
    # 若读取失败则输出无出库记录
    except FileNotFoundError:
        text_outgoing_view.delete(1.0, tk.END)  # 清空文本框内容
        text_outgoing_view.insert(tk.END, f"{datenow} 今日尚无出库记录")    # 在文本框中提示无今日出库记录

def record_outgoing(entry_item, entry_quantity, entry_unit, entry_handler, entry_approver, text_view, root):
    '''
    当按钮被点击时
    记录出库信息
    '''
    time_str = datetime.now().strftime("%H:%M:%S")
    item = entry_item.get() # 物品
    quantity = entry_quantity.get() # 数量
    unit = entry_unit.get() # 单位
    handler = entry_handler.get()   # 经办人
    approver = entry_approver.get() # 审批人
    
    if item and quantity and unit and handler and approver:
        try:
            quantity = int(quantity)
            datenow = datetime.now().strftime("%Y/%m/%d")
            date = datetime.now().strftime("%Y/%m")
            os.makedirs(f"出库/{date}", exist_ok=True)
            file_path = f"出库/{datenow}.xlsx"
            
            try:
                df = pd.read_excel(file_path)
            except FileNotFoundError:
                df = pd.DataFrame(columns=["出库时间", "物品", "数量", "单位", "经办人", "审批人"])
                
            new_record = pd.DataFrame({
                "出库时间": [time_str],
                "物品": [item],
                "数量": [quantity],
                "单位": [unit],
                "经办人": [handler],
                "审批人": [approver]
            })
            df = pd.concat([df, new_record], ignore_index=True)
            df.to_excel(file_path, index=False)
            messagebox.showinfo("成功", "出库记录已保存！")
            show_outgoing_records(text_view, root)
        except ValueError:
            messagebox.showerror("错误", "数量必须为整数！")
    else:
        messagebox.showerror("错误", "请输入完整信息！")

def outgoing(root, out_tab):
    text_outgoing_view = tk.Text(out_tab, height=15)
    text_outgoing_view.pack(fill=tk.X, padx=5, pady=5)

    show_outgoing_records(text_outgoing_view, root)

    out_input_frame = ttk.Frame(out_tab)
    out_input_frame.pack(fill=tk.X, padx=5, pady=5)

    ttk.Label(out_input_frame, text="物品:").grid(row=0, column=0)
    entry_outgoing_item = ttk.Entry(out_input_frame)
    entry_outgoing_item.grid(row=0, column=1, padx=5)

    ttk.Label(out_input_frame, text="数量:").grid(row=0, column=2)
    entry_outgoing_quantity = ttk.Entry(out_input_frame, width=6)
    entry_outgoing_quantity.grid(row=0, column=3, padx=5)

    ttk.Label(out_input_frame, text="单位:").grid(row=0, column=4)
    entry_outgoing_unit = ttk.Entry(out_input_frame, width=6)
    entry_outgoing_unit.grid(row=0, column=5, padx=5)

    ttk.Label(out_input_frame, text="经办人:").grid(row=0, column=6)
    entry_outgoing_handler = ttk.Entry(out_input_frame)
    entry_outgoing_handler.grid(row=0, column=7, padx=5)

    ttk.Label(out_input_frame, text="审批人:").grid(row=0, column=8)
    entry_outgoing_approver = ttk.Entry(out_input_frame)
    entry_outgoing_approver.grid(row=0, column=9, padx=5)

    out_button_frame = ttk.Frame(out_tab)
    out_button_frame.pack(fill=tk.X, padx=5, pady=5)

    button_record_outgoing = ttk.Button(
        out_button_frame,
        text="登记出库",
        command=lambda: (record_outgoing(
            entry_outgoing_item,
            entry_outgoing_quantity,
            entry_outgoing_unit,
            entry_outgoing_handler,
            entry_outgoing_approver,
            text_outgoing_view,
            root
        ))
    )
    button_record_outgoing.pack(side=tk.LEFT, padx=10)

    ttk.Button(out_button_frame, text="退出系统",
            command=root.destroy).pack(side=tk.RIGHT, padx=10)